#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "PopupAttachmentMsg.hpp"

using namespace std;
using namespace Popup;

AttachmentMsg::AttachmentMsg(const Message *p_message)
: AbstractMessage(POPUP_MSG_TYPE_ATTACHMENT), sendinfo(0)
{
  AbstractMessage::deserialize(p_message);
}

bool AttachmentMsg::onSend()
{
  bool _rc = true;

  _rc &= payloadAddLongLong(MSGID, sendinfo->messageID);
  _rc &= payloadAddLongLong(ATTACHMENTID, sendinfo->attachmentID);
  _rc &= payloadAddLong(TARGETS, sendinfo->targets);
  _rc &= payloadAddLong(FRAMENO, sendinfo->frameNo);
  _rc &= payloadAddLong(FRAMESIZE, frameSize);
  _rc &= payloadAddFromFile(RAWDATA, sendinfo->file, frameSize);

  // In case this is the first frame, we send a few more information
  if (_rc && sendinfo->frameNo == 1) {
    _rc &= payloadAddLong(TOTALSIZE, sendinfo->totalSize);
    _rc &= payloadAddString(FILENAME, PopupUtils::basename(sendinfo->filepath));
    _rc &= payloadAddLong(NBFRAMES, sendinfo->totalNbFrames);
    _rc &= payloadAddLongLong(CHECKSUM, sendinfo->checksum);
  }

  return _rc;
}

bool AttachmentMsg::onReceive()
{
  bool _rc = true;

  _rc &= payloadGetLongLong(MSGID, recvinfo.messageID);
  _rc &= payloadGetLongLong(ATTACHMENTID, recvinfo.attachmentID);
  _rc &= payloadGetLong(TARGETS, recvinfo.targets);
  _rc &= payloadGetLong(FRAMENO, recvinfo.frameNo);
  _rc &= payloadGetLong(FRAMESIZE, frameSize);

  if (_rc && recvinfo.frameNo == 1) {
    _rc &= payloadGetLong(TOTALSIZE, recvinfo.totalSize);
    _rc &= payloadGetString(FILENAME, recvinfo.filepath);
    _rc &= payloadGetLong(NBFRAMES, recvinfo.totalNbFrames);
    if (!payloadGetLongLong(CHECKSUM, recvinfo.checksum)) {
      recvinfo.checksum = 0;
    }
  }

  return _rc;
}

bool AttachmentMsg::getRawData(PopupUtils::FileStream *p_file) const {
  return payloadDumpFieldToFile(RAWDATA, p_file);
}
